import { defineStore } from 'pinia'
import { getMemberBalance } from '@/api/common'
import Cookies from 'js-cookie'
import { useRouter } from 'vue-router'

const router = useRouter()

export const useUserStore = defineStore('user', {
  persist: true,
  state() {
    // 定义状态属性的方法，返回值为定义的状态属性对象
    return {
      user: {
        companyId: null,
        email: null,
        imageUrl: null,
        mobile: null,
        nickName: null,
        realName: null,
        registerType: null,
        storeId: null,
        id: null,
        username: null,
        refleshTime: null,
        balanceMoney: 0,
      },
    }
  },
  getters: {
    getUser() {
      return this.user
    },
  },
  actions: {
    async isLogin() {
      if (!!Cookies.get('token')) {
        if (
          this.getUser?.id === null ||
          this.getUser?.refleshTime === null ||
          new Date().getTime() - this.getUser?.refleshTime > 1000 * 60 * 60 * 24
        ) {
          const res = await getMemberBalance()
          if (res.code === 20000) {
            console.log(res.data)
            this.user = {
              ...res.data,
              refleshTime: new Date().getTime(),
            }
            return this.user
          }
          return {
            companyId: null,
            email: null,
            imageUrl: null,
            mobile: null,
            nickName: null,
            realName: null,
            registerType: null,
            storeId: null,
            id: null,
            username: null,
            refleshTime: null,
            balanceMoney: 0,
          }
        }
        return Promise.resolve(this.user)
      }
      return Promise.resolve(false)
    },
    removeUser() {
      this.user = {
        companyId: null,
        email: null,
        imageUrl: null,
        mobile: null,
        nickName: null,
        realName: null,
        registerType: null,
        storeId: null,
        id: null,
        username: null,
        refleshTime: null,
        balanceMoney: 0,
      }
    },
  },
})
